package handler

import (
	"litetalk/logic"
	"litetalk/proto"
	"net/http"

	"github.com/gin-gonic/gin"
)

const (
	CodeSuccess      = 0
	CodeFail         = 1
	CodeUnknownError = -1
	CodeSessionError = -200
)

var msgCodeMap = map[int]string{
	CodeSuccess:      "success",
	CodeFail:         "fail",
	CodeUnknownError: "unknow error",
	CodeSessionError: "session error",
}

var logicRpc = &logic.LogicLocal

func ResponseWithCode(c *gin.Context, msgCode int, msg interface{}, data interface{}) {
	if msg == nil {
		if val, ok := msgCodeMap[msgCode]; ok {
			msg = val
		} else {
			msg = msgCodeMap[msgCode]
		}
	}
	c.AbortWithStatusJSON(http.StatusOK, gin.H{
		"code":    msgCode,
		"message": msg,
		"data":    data,
	})
}

func FailWithMsg(c *gin.Context, msg interface{}) {
	ResponseWithCode(c, CodeFail, msg, nil)
}

func SuccessWithMsg(c *gin.Context, msg interface{}, data interface{}) {
	ResponseWithCode(c, CodeSuccess, msg, data)
}

func CheckAuthWithFail(authToken string, c *gin.Context) bool {
	args := &proto.CheckAuthReq{
		AuthToken: authToken,
	}
	reply := &proto.CheckAuthRep{}
	if err := logicRpc.CheckAuth(args, reply); err != nil {
		FailWithMsg(c, err.Error())
		return false
	}
	return true
}

func CheckAuth(authToken string) (userId uint, err error) {
	args := &proto.CheckAuthReq{
		AuthToken: authToken,
	}
	reply := &proto.CheckAuthRep{}
	if err := logicRpc.CheckAuth(args, reply); err != nil {
		return 0, err
	}
	return reply.UserId, err
}
